# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html

from openpyxl import Workbook
import csv
import json,codecs
import os
from service.movieservice import MovieService

class MoviedatasPipeline(object):
    #（2）输出到表格
    # def __init__(self):
    #     self.wb=Workbook()
    #     self.ws=self.wb.active
    #     #设置表头
    #     self.ws.append(['电影名', '电影地址', '上映时间', '主演'])

    #(4)将文件写入json
    # def __init__(self):
    #     self.file=codecs.open('movie.json','w',encoding='utf-8')
    #     pass




    def process_item(self, item, spider):

        # （2）写入行
        # line=[item['filmname'][0:100],item['var_url'][0],item['filmdate'][0],item['major'][0:100]]
        # self.ws.append(line)

        #（1）将信息输出到控制台
        # print('电影名为：{}'.format(item['filmname']))
        # print('电影地址为：{}'.format(item['var_url']))
        # print('电影上映时间为：{}'.format(item['filmdate']))
        # print('电影主演为：{}'.format(item['major']))

        #(3)将数据写入csv
        # f=open(file='movie.csv',mode='a+',newline='',encoding='utf-8')
        # wirter=csv.writer(f)
        # wirter.writerow(['电影名','影片地址','上映时间','主演'])
        # wirter.writerow([item['filmname'],item['var_url'],item['filmdate'],item['major']])

        #(4)将数据写入json文件
        # line=json.dumps(dict(item),ensure_ascii=False)+'\n'
        # self.file.write(line)


        #(5)将数据写入txt
        # fileurl=('movie.txt')
        # with open(fileurl,'a+',encoding='utf-8') as file:
        #     file.write(item['filmname'][0:100]+'\n')
        #     file.write(item['var_url'][0]+'\n')
        #     file.write(item['filmdate'][0]+'\n')
        #     file.write(item['major'][0:100]+'\n\n')
        #     pass

        #保存到数据库
        var_MovieService=MovieService()
        var_MovieService.movieSaveToDB(item)

        return item



        # 保存xlsx文件
    # def close_spider(self, spider):
    #     self.wb.save('movie.xlsx')




